/**
 * 该方法库用于替换zepto方法
 */


/* eslint-disable */
import {KgMobileCall} from "../mobilecall/mobilecall-2.2";
import uuid from "uuid";
let class2type = {},
    toString = class2type.toString;

let ua = navigator.userAgent;

"Boolean Number String Function Array Date RegExp Object Error Undefined"
    .split(" ")
    .forEach(name => {
        class2type["[object " + name + "]"] = name.toLowerCase();
    });

export let sysVersion = (function() {
    //获取系统版本
    let v = ua.match(/\(.*(Android\s+[\d\.]+|OS\s+[\d\_]+).*?\)/i);
    v = v && v.length >= 2 ? v[1] : "";
    return v;
})();

/**
 * 类型检测
 * @param {any} obj
 * @return {string}
 */
export function type(obj) {
    return obj === null ? String(obj) : class2type[toString.call(obj)] || "object";
}

/**
 * 是否为函数
 * @param {any} value
 */
export function isFunction(value) {
    return type(value) === "function";
}
/**
 * 是否为window对象
 * @param {any} obj
 */
export function isWindow(obj) {
    return obj && obj !== null && obj == obj.window;
}

/**
 * 是否为对象
 * @param {any} obj
 */
export function isObject(obj) {
    return type(obj) === "object";
}

/**
 * 是否为数组
 * @param {*} obj
 */
export function isArray(obj) {
    return type(obj) === "array";
}

/**
 * 是否为纯对象
 * 非window对象且继承自Object
 * @param {*} obj
 */
export function isPlainObject(obj) {
    return obj && isObject(obj) && !isWindow(obj) && Object.getPrototypeOf(obj) == Object.prototype;
}

/**
 * 是否为空对象
 * @param {*} obj
 */
export function isEmptyObject(obj) {
    for (let name in obj) {
        if (Object.hasOwnProperty.call(obj, name)) {
            return false;
        }
    }
    return true;
}

/**
 * 是否为类（伪）数组
 * @param {Object} obj
 */
export function likeArray(obj) {
    return typeof obj.length === "number";
}

/**
 * 去除空格
 * @param {String} str
 * @return {String}
 */
export function trim(str) {
    return str === null ? "" : String.prototype.trim.call(str);
}

/**
 * 当前环境变量
 */
export const env = (function() {
    let hostname = window.location.hostname;
    let result = "pro";
    let regResult = hostname.match(/(\w+)\.(\w+)\./) || [];
    let firstHost = regResult[1];
    let secondHost = regResult[2];
    if (hostname == "localhost") {
        return "dev";
    }

    switch (firstHost) {
        case "mforrel":
        case "mfortest":
        case "forrel":
            //预发布
            result = "pre";
            break;

        case "mrtest":
        case "mrtest1":
        case "mrtest2":
        case "mrtest3":
        case "mrtest4":
            //测试环境
            result = "test";
            break;

        default: {
            if (secondHost === "fxwork") {
                result = "dev";
            } else {
                result = "pro";
            }
            break;
        }
    }

    return result;
})();

/**
 * 自动根据环境获取域名
 * @param {Object} config
 * @param {String} config.dev
 * @param {String} config.test
 * @param {String} config.pre
 * @param {String} config.pro
 * @returns {String}
 */
export function configDomain(config) {
    try {
        if (config) {
            let envRes = "";
            let matchArr;
            let domain = window.location.host;
            if (/^kf[a-z]+/.test(domain)) {
                envRes = "dev";
            } else if (/^fx\d+|^ci-|^uiautotest/.test(domain) && !/^fx140/.test(domain)) {
                envRes = "test";
            } else {
                matchArr = domain.match(/^([\w\-]+)\./);
                if (matchArr) {
                    envRes = matchArr[1];
                }
            }
            if (config) {
                return config[envRes] ? config[envRes] : config["fanxing"];
            }
            return envRes;
        }
    } catch (error) {}
}

/**
 *
 * @param {array} array
 */
export function arrayToSpacing(array) {
    if (Array.isArray(array)) {
        return array.join(" ");
    }
    return array;
}

/**
 * 当前系统配置
 */
export const os = (function($) {
    let osInner = {},
        android = ua.match(/(Android);?[\s\/]+([\d.]+)?/),
        ipad = ua.match(/(iPad).*OS\s([\d_]+)/),
        ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/),
        iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/),
        SafariBrowser = new RegExp("Safari/", "gi").test(ua),
        UCBrowser = new RegExp("UCBrowser", "gi").test(ua),
        MQQBrowser = new RegExp("MQQBrowser", "gi").test(ua),
        MicroMessenger = new RegExp("MicroMessenger", "gi").test(ua),
        QQ = new RegExp("QQ/", "gi").test(ua),
        Weibo = new RegExp("Weibo", "gi").test(ua),
        Mobile = ua.toLowerCase().indexOf("mobile") !== -1;

    if (android) {
        osInner.android = true;
        osInner.version = android[2];
    }
    if (iphone && !ipod) {
        osInner.ios = osInner.iphone = true;
        osInner.version = iphone[2].replace(/_/g, ".");
    }
    if (ipad) {
        osInner.ios = osInner.ipad = true;
        osInner.version = ipad[2].replace(/_/g, ".");
    }

    osInner.SafariBrowser = SafariBrowser;
    osInner.UCBrowser = UCBrowser;
    osInner.MQQBrowser = MQQBrowser;
    osInner.MicroMessenger = MicroMessenger;
    osInner.QQ = QQ;
    osInner.Weibo = Weibo;
    osInner.Mobile = Mobile;
    osInner.sysVersion = sysVersion;

    return osInner;
})();

/**
 * 格式化JSON
 */
export const parseJSON = JSON.parse;

/**
 * 是否酷狗APP
 */
export const boolKg = KgMobileCall.isAndroid || KgMobileCall.isIOS || ua.indexOf("KGBrowser") > 0; //判断是否酷狗安卓客户端

/**
 *
 * 短视频APP
 */
export const boolDk = new RegExp("kgshortvideo", "gi").test(ua);

/**
 * 是否繁星APP
 */
export const boolFX = new RegExp("FanXing", "gi").test(ua); //判断是否繁星客户端
/**
 * 是否酷狗唱唱APP
 *
 */
export const boolSingle = ua.indexOf("KTVBrowser") > 0;
/**
 * 是否在APP内
 */
export const boolApp = boolKg || boolFX || boolDk;

/**
 * 补零操作
 * @param {Number} n
 */
export function addZero(n) {
    return !isNaN(n) && typeof n === "number" ? (n.toString().length <= 1 ? "0" : "") + n : n;
}

/**
 * 日期格式化
 * @param {Date|number} date
 * @param {String} format
 */
export function dateFormat(date, format) {
    if (!date) {
        return date;
    }
    if (type(date) === "number") {
        date = new Date(fillTimestamp(date));
    }
    if (date.toString() !== "Invalid Date") {
        let y = date.getFullYear().toString(),
            M = addZero(date.getMonth() + 1),
            d = addZero(date.getDate()),
            h = addZero(date.getHours()),
            m = addZero(date.getMinutes()),
            s = addZero(date.getSeconds()),
            S = addZero(date.getMilliseconds()),
            q = Math.ceil(M / 3).toString(); //季度

        let arrayObj = [
            {
                value: y,
                regular: /(y{1,4})/gi,
                max: 4
            },
            {
                value: M,
                regular: /(M{1,2})/g
            },
            {
                value: d,
                regular: /(d{1,2})/gi
            },
            {
                value: h,
                regular: /(h{1,2})/gi
            },
            {
                value: m,
                regular: /(m{1,2})/g
            },
            {
                value: s,
                regular: /(s{1,2})/g
            },
            {
                value: S,
                regular: /(S{1,3})/g,
                max: 3
            },
            {
                value: q,
                regular: /(q{1,2})/g
            }
        ];

        arrayObj.forEach(function(o) {
            if (o.regular.test(format)) {
                let v = RegExp.$1,
                    maxLength = o.max || 2;
                format = format.replace(v, o.value.substring(maxLength - v.length));
            }
        });
        return format;
    }
    return date;
}

/**
 * 设置图片地址后缀
 * @param {String} imgSrc
 * @param {String} sizeType
 */
export function setImgSize(imgSrc, sizeType) {
    if (!imgSrc) {
        return "";
    }
    let sFormat = "";
    if (imgSrc.indexOf(sizeType) > 0 || /fxusercmdavata/i.test(imgSrc)) {
        return imgSrc;
    }
    if (/fxmobilecover|fxroomcover/i.test(imgSrc)) {
        sizeType = "253x196";
    } else if (/v_snapshot/i.test(imgSrc)) {
        sizeType = "352x220";
    }
    sFormat = imgSrc.substr(imgSrc.lastIndexOf("."));

    return imgSrc + "_" + sizeType + sFormat;
}

/**
 * 补充时间戳长度
 * @param {Number} timeStamp
 * @returns {Number}
 */
export function fillTimestamp(timeStamp, length = 13) {
    let strTimeStamp = timeStamp + "";
    let strLength = strTimeStamp.length;
    if (strLength !== length) {
        for (let i = 0; i < Math.abs(strLength - length); i++) {
            strTimeStamp += "0";
        }
    }

    return strTimeStamp.substr(0, length) * 1;
}

/**
 * cookies操作
 */
export const CookieUtil = {
    /**
     * @param {string} name
     * @return {object}
     */
    get: function(name) {
        let cookie = document.cookie,
            cookieName = encodeURIComponent(name) + "=",
            cookieStart = cookie.indexOf(cookieName),
            cookieValue = null;

        if (cookieStart > -1) {
            let cookieEnd = cookie.indexOf(";", cookieStart);
            if (cookieEnd == -1) {
                cookieEnd = cookie.length;
            }
            cookieValue = unescape(cookie.substring(cookieStart + cookieName.length, cookieEnd));
        }
        return cookieValue;
    },
    /*$.CookieUtil.set({
     name:"aa",
     value:123,
     expires:new Date().getTime()+10000,
     path:"",
     domain:".kugou.com",
     secure:0
     };**/
    /**
     * @param {object} obj
     * @param {string} [obj.name]
     * @param {string} [obj.value]
     * @param {string} [obj.expires]
     * @param {string} [obj.path]
     * @param {string} [obj.domain]
     * @param {string} [obj.secure]
     */
    set: function(obj, willEncode = true) {
        let params = {
            name: obj.name || "",
            value: obj.value || "",
            expires: obj.expires || "",
            path: obj.path || "",
            domain: obj.domain || "",
            secure: obj.secure || ""
        };
        let cookieText = encodeURIComponent(params.name) + "=" + encodeURIComponent(params.value);
        if (!willEncode) {
            //不转义
            cookieText = params.name + "=" + params.value;
        }

        if (params.expires instanceof Date) {
            cookieText += "; expires=" + params.expires.toGMTString();
        }

        if (params.path) {
            cookieText += "; path=" + params.path;
        }

        if (params.domain) {
            cookieText += "; domain=" + params.domain;
        }

        if (params.secure) {
            cookieText += "; secure=";
        }
        document.cookie = cookieText;
    },
    //$.CookieUtil.del("KuGoo","/",".kugou.com",0)
    /**
     * @param {string} name
     * @param {string} path
     * @param {string} domain
     * @param {(number|string)} secure
     */
    del: function(name, path, domain, secure) {
        let exp = new Date();
        exp.setTime(exp.getTime() - 1);
        let cval = this.get(name);
        this.set({
            name,
            cval,
            exp,
            path,
            domain,
            secure
        });
    },
    /**
     * @param {string} name
     * @param {string} item
     */
    getValue: function(name, item) {
        let cookieArr = document.cookie.match(new RegExp("(^|\\s)" + name + "=([^;]*)", "i"));
        let cookieValue = cookieArr ? unescape(cookieArr[2]) : "";
        if (item && cookieValue) {
            let value = cookieValue.match(new RegExp("(^|\\&)" + item + "=([^\\&]*)", "i"));
            cookieValue = value ? value[2] : "";
        }
        return cookieValue;
    }
};

/**
 * AJAX
 */
export const ajax = (function() {
    //默认请求参数
    let _options = {
        url: null,
        type: "get",
        data: null,
        dataType: "json",
        jsonp: "callback",
        jsonpCallback: "jsonpCallback",
        async: true,
        cache: true,
        timeout: null,
        contentType: "application/x-www-form-urlencoded",
        success: null,
        fail: null
    };

    // json转化为字符串
    // let _param = (data) => {
    //     let str = "";
    //     if (!data || isEmptyObject(data)) {
    //         return str;
    //     }
    //     for (let key in data) {
    //         if (Object.prototype.hasOwnProperty.call(data, key) && !isObject(data[key])) {
    //             str += key + "=" + data[key] + "&";
    //         } else {
    //             str += _param(data[key]);
    //         }
    //     }
    //     // console.log(str)
    //     // str = str.slice(0, -1);
    //     return str;
    // };
    let serialize = (params, data, scope) => {
        let otype,
            hash = isObject(data);
        for (let key in data) {
            if (Object.prototype.hasOwnProperty.call(data, key)) {
                let value = data[key];
                otype = type(value);
                if (scope) {
                    key = `${scope}[${hash || otype == "object" || otype == "array" ? key : ""}]`;
                }
                if (otype == "array" || otype == "object") {
                    serialize(params, value, key);
                } else {
                    params.add(key, value);
                }
            }
        }
    };
    let _param = data => {
        let params = [];
        params.add = function(key, value) {
            if (isFunction(value)) {
                value = value();
            }
            if (value === null) {
                value = "";
            }
            this.push(`${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
        };
        serialize(params, data);
        return params.join("&").replace(/%20/g, "+");
    };

    // jsonp处理函数
    function _sendJsonpRequest(url, callbackName, succCallback) {
        let script = document.createElement("script");

        script.type = "text/javascript";
        script.src = url;

        document.body.appendChild(script);
        // 如果用户自己定义了回调函数，就用自己定义的，否则，调用success函数
        window[callbackName] = window[callbackName] || succCallback;
    }

    return function(options) {
        // 没有传参或者没有url，抛出错误
        if (!options || !options.url) {
            console.log("没有传参或者没有url！");
        }

        // 继承操作
        options = Object.assign({}, _options, options);
        options.type = options.type.toUpperCase();

        /*jsonp部分，直接返回*/
        if (options.dataType === "jsonp") {
            let param = _param(options.data);
            let jsonpUrl =
                options.url.indexOf("?") > -1
                    ? options.url + "?" + param
                    : options.url + "?" + options.jsonp + "=" + options.jsonpCallback + "&" + param;

            _sendJsonpRequest(jsonpUrl, options.jsonpCallback, options.success);

            return;
        }

        //XMLHttpRequest传参无影响
        let xhr = new XMLHttpRequest();

        // get搜索字符串
        let search = "";

        // 将data序列化
        let param = _param(options.data);

        if (options.type === "GET") {
            search = (options.url.indexOf("?") > -1 ? "&" : "?") + param;
            if (!options.cache) {
                search += "&t=" + Date.now();
            }

            param = null;
        }

        xhr.open(options.type, options.url + search, options.async);

        // options.complete = options.complete || options.success;

        xhr.onreadystatechange = () => {
            if (xhr.readyState == 4) {
                if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                    let text = xhr.responseText;
                    // json格式转换
                    if (!isPlainObject(text)) {
                        try {
                            text = parseJSON(text);
                        } catch (error) {}
                    }

                    if (isFunction(options.success)) {
                        options.success(text, xhr.status);
                    }
                } else if (typeof options.fail === "function") {
                    options.fail("获取失败", 500);
                }
                if (isFunction(options.complete)) {
                    options.complete(xhr.responseText, xhr.status);
                }
            }
        };

        xhr.setRequestHeader("content-type", options.contentType);

        // get请求时param时null
        xhr.send(param);

        // 如果设置了超时，就定义
        if (type(options.timeout) === "number") {
            if (xhr.timeout) {
                xhr.timeout = options.timeout;
            } else {
                setTimeout(function() {
                    xhr.abort();
                }, options.timeout);
            }
        }
    };
})();

/**
 * 合并对象
 */
export const extend = Object.assign;

/**
 * 设置节点属性
 * @param {HTMLElement} node
 * @param {string} name
 * @param {string} value
 */
export function setAttribute(node, name, value) {
    return value === null ? node.removeAttribute(name) : node.setAttribute(name, value);
}

/**
 * 轮询设置节点属性
 * @param {HTMLElement} node
 * @param {object} attrObj
 */
export function setAttrForEach(node, attrObj) {
    if (isPlainObject(attrObj)) {
        for (let attr in attrObj) {
            if (Object.prototype.hasOwnProperty.call(attrObj, attr)) {
                setAttribute(node, attr, attrObj[attr]);
            }
        }
    }
}

//获取手机版本
function getDeviceModel() {
    let deviceModel = "";
    if (os.ios) {
        return "iphone";
    } else if (os.android) {
        deviceModel = ua.match(/;\s+(?:.*?);(.*?)\s*Build/i);
        if (deviceModel.length >= 2) {
            deviceModel = deviceModel[1];
        }
    }
    return deviceModel;
}

export let device = getDeviceModel();

export let imageCDN = ["https://s4fx.kgimg.com"];

//随机获取图片CDN地址
export function getImgCdnAddr(cdnList = imageCDN) {
    let length = cdnList.length;
    let index = Math.floor(Math.random() * length);
    return cdnList[index];
}

/**
 * //按对象属性字母升序排序
 * @param {Object} obj
 */
export function objKeySort(obj) {
    let newkey = Object.keys(obj).sort(); //先用Object内置类的keys方法获取要排序对象的属性名，再利用Array原型上的sort方法对获取的属性名进行排序，newkey是一个数组
    let newObj = {}; //创建一个新的对象，用于存放排好序的键值对
    for (let i = 0; i < newkey.length; i++) {
        //遍历newkey数组
        let _val = obj[newkey[i]];
        if (undefined !== _val && null !== _val) {
            newObj[newkey[i]] = obj[newkey[i]]; //向新创建的对象中按照排好的顺序依次增加键值对
        }
    }
    return newObj; //返回排好序的新对象
}

/**
 * 按数组内的对象key值排序
 * @param {*} arr 源数组
 * @param {*} keyName key值
 * @param {*} sortType 排序类型，默认(desc)升序
 */
export function arrSortByKey(arr, keyName, sortType = "desc") {
    let r = sortType === "desc" ? 1 : -1;
    if (type(arr) !== "array" || arr.length <= 1) {
        return arr;
    }
    return arr.sort((a, b) => {
        return (a[keyName] - b[keyName]) * r;
    });
}

/**
 *
 * @param {HTMLElement} el
 */
export function padFixOrAbsElement(el) {
    let nodeUuid = el.dataset.uuid;
    if (nodeUuid && document.querySelectorAll(`[data-uuid="${nodeUuid}"]`).length == 2) {
        return;
    }
    el.classList.add("padding-el");
    let $rect = el.getBoundingClientRect();
    //let style = el.style;
    el.setAttribute("data-uuid", uuid.v1());
    let padEl = el.cloneNode();
    padEl.style.position = "relative";
    padEl.style.visibility = "hidden";
    padEl.style.display = "block";
    //padEl.style.width = `${$rect.width}px`;
    padEl.style.height = `${$rect.height}px`;
    el.parentNode.insertBefore(padEl, el);
    return padEl;
}

export function isNewWeixin() {
    if (!os.MicroMessenger) {
        return false;
    }
    const curVersion = os.version;
    const compare = compareVersion(curVersion, "6.5.16");

    if (compare > 0) {
        return true;
    }
    return false;
}

export function compareVersion(v1, v2) {
    let _v1 = v1.split("."),
        _v2 = v2.split("."),
        _r = _v1[0] - _v2[0];

    return _r == 0 && v1 != v2
        ? compareVersion(_v1.splice(1).join("."), _v2.splice(1).join("."))
        : _r;
}

export const platformId = (function() {
    if (boolFX) {
        return os.android ? 1 : os.ipad ? 3 : 2;
    } else if (boolKg) {
        return os.android ? 5 : 6;
    }
    return 18;
})();

/**
 * http 资源切换到 https
 * http://s10.fxwork.kugou.com > https://s10.fxwork.kugou.com
 * http://s[1-5].fx.kgimg.com > https://s3fx.kgimg.com
 * http://p[1-5].fx.kgimg.com > https://p3fx.kgimg.com
 * @param {string} url URL
 */
export function switchHttps(url) {
    if (typeof url !== "string") {
        return url;
    }
    if (url.indexOf("http://s10.fxwork.kugou.com") === 0) {
        return url.replace(/^http/, "https");
    } else if (url.indexOf("http://image.fanxing.kugou.com") === 0) {
        return url.replace("http://image.fanxing.kugou.com", "https://s3fx.kgimg.com");
    } else if (url.indexOf("http://imge.kugou.com") === 0) {
        return url.replace("http://imge.kugou.com", "https://p3fx.kgimg.com");
    } else if (url.indexOf("http://fxvideoimg.bssdl.kugou.com") === 0) {
        return url.replace(
            "http://fxvideoimg.bssdl.kugou.com",
            "https://fxbssdl.kgimg.com/bss/fxvideoimg/"
        );
    } else if (url.indexOf("http://fxbssdl.kgimg.com") === 0) {
        return url.replace("http://", "https://");
    } 
    // else if (url.indexOf("http://album.bssdl.kugou.com") === 0) {
    //     return url.replace("http://album.bssdl.kugou.com", "https://fxbssdl.kgimg.com/bss/album");
    // } 
    else if (url.indexOf("http://") === 0) {
        if (url.indexOf("/v2/") >= 0) {
            return url.replace(/^http:\/\/[sp][1-5]\.fx\.kgimg\.com/, "https://p3fx.kgimg.com");
        }
        return url.replace(/^http:\/\/([sp])[1-5]\.fx\.kgimg\.com/, "https://$13fx.kgimg.com");
    }

    return url;
}

export function getUUID() {
    let d = Date.now();
    let uid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
        /* eslint-disable no-bitwise */
        let r = ((d + Math.random() * 16) % 16) | 0;
        d = Math.floor(d / 16);
        return (c == "x" ? r : (r & 0x7) | 0x8).toString(16);
    });
    return uid;
}

export const PAYMENT_IDS = {
    WX: ['H', '5', 'W', 'x', 'P', 'a', 'y'].join(''),
    ALI: ['H', '5', 'A', 'l', 'i', 'P', 'a', 'y'].join(''),
    APP_WX: ['A', 'p', 'p', 'W', 'x', 'P', 'a', 'y'].join(''),
    APP_ALI: ['A', 'p', 'p', 'A', 'l', 'i', 'P', 'a', 'y'].join('')
};

export default {
    env,
    arrayToSpacing,
    addZero,
    dateFormat,
    setImgSize,
    CookieUtil,
    ajax,
    boolKg,
    boolFX,
    boolDk,
    boolSingle,
    os,
    parseJSON,
    isPlainObject,
    type,
    isFunction,
    extend,
    platformId,
    switchHttps, PAYMENT_IDS
};
